package com.example.question.tree.tree3;

import com.example.question.tree.tree1.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2023-07-15
 * @Author Jonathan
 */
public class Code11_501 {

    private int preNum = 0;
    private int count = 0;
    private int maxCount = 0;
    private List<Integer> ret = new ArrayList<>();

    public int[] findMode(TreeNode root) {
        if (root == null) return null;
        int[] ans = new int[ret.size()];
        for (int i = 0; i < ret.size(); i++) {
            ans[i] = ret.get(i);
        }
        return ans;

    }

    // 二叉搜索树的中序遍历就是有序的
    private void dfs(TreeNode node) {
        if (node == null) return;
        dfs(node.left);
        update(node.val);
        dfs(node.right);
    }

    private void update(int val) {
        if (val == preNum) {
            count++;
        } else {
            preNum = val;
            // 重新计数
            count = 1;
        }

        if (count == maxCount) {
            ret.add(val);
        } else if (count > maxCount) {
            ret.clear();
            ret.add(val);
            maxCount = count;
        }
    }
}
